import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Menu } from 'antd'
import type { MenuProps } from 'antd'
import { getLeftMenus } from '@/service/api'
import { searchLeftMenus } from '@/utils/util'
import { setRouteMenuList } from '@/redux/modules/menu'
import { useDispatch } from 'react-redux'
import './index.scss'

type MenuItem = Required<MenuProps>['items'][number]

const LayoutMenu = () => {
  const { pathname } = useLocation()
  const [openKeys, setOpenKeys] = useState<string[]>([])
  const [selectedKeys, setSelecetedKeys] = useState<string[]>([pathname])
  const [menuList, setMenuList] = useState<MenuItem[]>([])
  const navigate = useNavigate()
  const dispatch = useDispatch()

  useEffect(() => {
    setSelecetedKeys([pathname])
    getLeftMenus().then(res => {
      setMenuList(searchLeftMenus(res.data))
      dispatch(setRouteMenuList(searchLeftMenus(res.data)))
    })
  }, [pathname])

  const clickMenu: MenuProps['onClick'] = ({ key }: { key: string }) => {
    navigate('/' + key)
  }
  const onOpenChange = (openKeys: string[]) => {
    if (openKeys.length === 0 || openKeys.length === 1) return setOpenKeys(openKeys)
    const latestOpenKey = openKeys[openKeys.length - 1]
    if (latestOpenKey.includes(openKeys[0])) return setOpenKeys(openKeys)
    setOpenKeys([latestOpenKey])
  }
  return (
    <div className="menu">
      <Menu
        theme="dark"
        mode="inline"
        triggerSubMenuAction="click"
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        items={menuList}
        onClick={clickMenu}
        onOpenChange={onOpenChange}
      ></Menu>
    </div>
  )
}

export default LayoutMenu
